package com.example.demo.controller;

import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UploadController {

    //用于接收文件
    @RequestMapping("/upload")
    public String upload(@RequestPart("filename") MultipartFile file,
                         HttpServletRequest request) throws IOException {
        String path = System.getProperty("user.dir")+"\\src\\main\\resources\\static\\images\\musicImg\\";
        String path2 = System.getProperty("user.dir")+"\\target\\classes\\static\\images\\musicImg\\";
        System.out.println(path);
        String nameAndType = file.getOriginalFilename();
        System.out.println(nameAndType);
        String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        System.out.println(ext);
        String newName = UUID.randomUUID().toString().replaceAll("-","")+"."+ext;
        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdirs();
        }
        file.transferTo(new File(realPath + "/" + newName));
        File realPath2 = new File(path2);
        if (!realPath2.exists()) {
            realPath2.mkdirs();
        }
        file.transferTo(new File(realPath2 + "/" + newName));
        return path;
    }

}
